/**
 * 
 */
package com.sandberg.shopper;

import com.sandberg.shopper.core.HelpScreen;
import com.sandberg.shopper.core.Utility;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * @author Jesper
 *
 */
public class ShopperCheapestActivity extends Activity {
	private float mValueAmount1 = 0.0f;
	private float mValuePrice1 = 0.0f;
	private float mValueAmount2 = 0.0f;
	private float mValuePrice2 = 0.0f;

	private final int DIALOG_WARNING = 1;
	private final int DIALOG_PRICE = 2;
	private final int DIALOG_HELP = 3;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(Property.LOGTAG, "Cheapest Started");
        setContentView(R.layout.cheapest);

        // Restore preferences
        SharedPreferences settings = getSharedPreferences(Property.SHARED_PREFS_NAME, 0);
        if (settings.getBoolean(Property.SHARED_STORE_FIELDS, true)) {
        	getStoredValues(settings);
        }
    }

    private void getStoredValues(SharedPreferences settings) {
        // Get amount1 value
        final EditText amount1 = (EditText) findViewById(R.id.editCheapestAmount1);
        String amountField1 = settings.getString(Property.SHARED_CHEAPEST_AMOUNT_1, "");
        amount1.setText(amountField1);
        // Get price1 value
        final EditText price1 = (EditText) findViewById(R.id.editCheapestPrice1);
        String priceField1 = settings.getString(Property.SHARED_CHEAPEST_PRICE_1, "");
        price1.setText(priceField1);
        // Get amount2 value
        final EditText amount2 = (EditText) findViewById(R.id.editCheapestAmount2);
        String amountField2 = settings.getString(Property.SHARED_CHEAPEST_AMOUNT_2, "");
        amount2.setText(amountField2);
        // Get price2 value
        final EditText price2 = (EditText) findViewById(R.id.editCheapestPrice2);
        String priceField2 = settings.getString(Property.SHARED_CHEAPEST_PRICE_2, "");
        price2.setText(priceField2);
    }

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	public void onCalculate(View target) {
		if (validateInput() == false) {
			showDialog(DIALOG_WARNING);
		} else {
			removeDialog(DIALOG_PRICE);
			showDialog(DIALOG_PRICE);
		}
	}

	public void deleteItem1(View target) {
		final EditText deleteAmountEdit = (EditText) findViewById(R.id.editCheapestAmount1);
		deleteAmountEdit.setText("");
		final EditText deletePriceEdit = (EditText) findViewById(R.id.editCheapestPrice1);
		deletePriceEdit.setText("");

		LinearLayout marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest1);
		marker.setBackgroundDrawable(null);
		marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest2);
		marker.setBackgroundDrawable(null);
    }

	public void deleteItem2(View target) {
		final EditText deleteAmountEdit = (EditText) findViewById(R.id.editCheapestAmount2);
		deleteAmountEdit.setText("");
		final EditText deletePriceEdit = (EditText) findViewById(R.id.editCheapestPrice2);
		deletePriceEdit.setText("");

		LinearLayout marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest1);
		marker.setBackgroundDrawable(null);
		marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest2);
		marker.setBackgroundDrawable(null);
    }

	private boolean validateInput() {
		String inputValue;
		int validFields = 0;
		
		final EditText amount1Edit = (EditText) findViewById(R.id.editCheapestAmount1);
		inputValue = amount1Edit.getText().toString();
		if (inputValue.length() > 0) {
			mValueAmount1 = Float.valueOf(inputValue);
			if (mValueAmount1 != 0) {
				validFields++;
			}
		} else {
			mValueAmount1 = 0;
		}

		final EditText price1Edit = (EditText) findViewById(R.id.editCheapestPrice1);
		inputValue = price1Edit.getText().toString();
		if (inputValue.length() > 0) {
			mValuePrice1 = Float.valueOf(inputValue);
			if (mValuePrice1 != 0) {
				validFields++;
			}
		} else {
			mValuePrice1 = 0;
		}

		final EditText amount2Edit = (EditText) findViewById(R.id.editCheapestAmount2);
		inputValue = amount2Edit.getText().toString();
		if (inputValue.length() > 0) {
			mValueAmount2 = Float.valueOf(inputValue);
			if (mValueAmount2 != 0) {
				validFields++;
			}
		} else {
			mValueAmount2 = 0;
		}

		final EditText price2Edit = (EditText) findViewById(R.id.editCheapestPrice2);
		inputValue = price2Edit.getText().toString();
		if (inputValue.length() > 0) {
			mValuePrice2 = Float.valueOf(inputValue);
			if (mValuePrice2 != 0) {
				validFields++;
			}
		} else {
			mValuePrice2 = 0;
		}

		if (validFields == 4) {
			return true;
		} else {
			return false;
		}
	}
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog = null;
	    switch(id) {
	    	case DIALOG_WARNING:
	    		// do the work to define the pause Dialog
	    		dialog = createWarning();
	    		break;
	    	case DIALOG_PRICE:
	    		// do the work to define the pause Dialog
	    		dialog = createPrice();
	    		break;
	    	case DIALOG_HELP:
	    		dialog = HelpScreen.createHelpScreen(this, R.string.help_cheapest);
	    		break;
	    }
	    return dialog;
	}
	
	private AlertDialog createWarning() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getResources().getString(R.string.cheapest_warning_text));
		builder.setCancelable(false);
		builder.setPositiveButton(getResources().getString(R.string.warning_button), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
					}
				});
		return builder.create();
	}

	private AlertDialog createPrice() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		String formatted;

		float price1 = mValuePrice1/mValueAmount1;
		float price2 = mValuePrice2/mValueAmount2;

		if (price1 > price2) {
			formatted = getResources().getString(R.string.cheapest_price_text);
			formatted = String.format(formatted, 2, Utility.round2digits(mValuePrice2/mValueAmount2));
			LinearLayout marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest1);
			marker.setBackgroundDrawable(null);
			marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest2);
			marker.setBackgroundResource(R.drawable.cheapest_marker_active);
		} else if (price1 < price2) {
			formatted = getResources().getString(R.string.cheapest_price_text);
			formatted = String.format(formatted, 1, Utility.round2digits(mValuePrice1/mValueAmount1));
			LinearLayout marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest1);
			marker.setBackgroundResource(R.drawable.cheapest_marker_active);
			marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest2);
			marker.setBackgroundDrawable(null);
		} else {
			formatted = getResources().getString(R.string.cheapest_equal_text);
			LinearLayout marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest1);
			marker.setBackgroundDrawable(null);
			marker = (LinearLayout) findViewById(R.id.linearLayoutCheapest2);
			marker.setBackgroundDrawable(null);
		}
				
		builder.setMessage(formatted);
		builder.setCancelable(false);
		builder.setPositiveButton(getResources().getString(R.string.ok_button), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
					}
				});
		return builder.create();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		menu.add(getResources().getString(R.string.option_menu_options))
			.setIcon(android.R.drawable.ic_menu_preferences)
			.setIntent(new Intent(this, ShopperSettingsActivity.class));

		menu.add(getResources().getString(R.string.option_menu_about))
			.setIcon(android.R.drawable.ic_menu_info_details)
			.setIntent(new Intent(this, ShopperAboutActivity.class));

		menu.add(getResources().getString(R.string.option_menu_help))
			.setIcon(android.R.drawable.ic_menu_help);

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		String title = (String) item.getTitle();
		if (title.compareTo(getResources().getString(R.string.option_menu_help)) == 0) {
			showDialog(DIALOG_HELP);
			return true;
		}
		return false;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
	 */
	@Override
	protected void onPause() {
    	// We need an Editor object to make preference changes.
    	SharedPreferences settings = getSharedPreferences(Property.SHARED_PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
		
        // Set amount1 value
        final EditText amount1 = (EditText) findViewById(R.id.editCheapestAmount1);
        String amountField1 = amount1.getText().toString();
    	editor.putString(Property.SHARED_CHEAPEST_AMOUNT_1, amountField1);

        // Get price1 value
        final EditText price1 = (EditText) findViewById(R.id.editCheapestPrice1);
        String priceField1 = price1.getText().toString();
    	editor.putString(Property.SHARED_CHEAPEST_PRICE_1, priceField1);

        // Set amount2 value
        final EditText amount2 = (EditText) findViewById(R.id.editCheapestAmount2);
        String amountField2 = amount2.getText().toString();
    	editor.putString(Property.SHARED_CHEAPEST_AMOUNT_2, amountField2);

        // Get price2 value
        final EditText price2 = (EditText) findViewById(R.id.editCheapestPrice2);
        String priceField2 = price2.getText().toString();
    	editor.putString(Property.SHARED_CHEAPEST_PRICE_2, priceField2);

    	editor.commit();

    	super.onPause();
	}
}
